package com.alan.springbootwp.controller;

import com.alan.springbootwp.service.MessageService;
import com.alan.springbootwp.util.WeiXinSignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Alan
 * @Description
 * @date 2020年03月30日 21:31
 */
@RestController
@RequestMapping(value = "weixin")
public class WeixinCoreController {

        private static Logger logger = LoggerFactory.getLogger(WeixinCoreController.class);

        @Autowired
        private WeiXinSignUtil weiXinSignUtil;

        @Autowired
        private MessageService messageService;

        @GetMapping(value="/access")
        public String WeChatInterface(HttpServletRequest request)throws Exception {
            System.out.println("-------------验证微信服务号信息开始----------");
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");

            logger.info("signature is :" + signature + "timestamp is" + timestamp + "nonce is :" + nonce);
            if (weiXinSignUtil.checkSignature(signature, timestamp, nonce)) {
                System.out.println("-----------验证微信服务号结束------------");
                return echostr;
            } else {

                // 此处可以实现其他逻辑
                logger.warn("不是微信服务器发过来的请求，请小心！");
                return null;
            }
        }


    /**
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @PostMapping(value = "/access")
    public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String result = messageService.handleMessage(request, response);

        messageService.responseStr(response, result);

    }

        @RequestMapping(value = "aa")
        public  String aa(){
            System.out.println("aaaaaa");
            return "sss";
        }
}
